package org.elepower.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.elepower.dao.*;
import org.elepower.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/task")
public class PsInspectiontask_mainController {

    @Autowired
    private Inspectiontask_mainDao inspectiontask_mainDao;
    @Autowired
    private PsInspectorDetailsDao inspectorDetailsDao;
    @Autowired
    private LineDao lineDao;
    @Autowired
    private InspectiontaskDetailsDao inspectiontaskDetailsDao;
    @Autowired
    private PoleDao poleDao;

    @RequestMapping("/index")
    public String index(ModelMap modelMap) throws Exception {
        return "system/inspectiontask_main/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, PsInspectiontask_main condition, HttpServletRequest request) throws Exception {

        Map<String, Object> map = new HashMap<>();

        Page<PsInspectiontask_main> pager = PageHelper.startPage(page, limit);
        List<PsInspectiontask_main> list = inspectiontask_mainDao.getCondition(condition);
        request.setAttribute("list",list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        map.put("count", pager.getTotal());
        return map;
    }

    @RequestMapping("/form")
    public String form() throws Exception{
        return "system/inspectiontask_main/form";
    }

    /**
     * 根据巡检员编号字符串分割数组
     * @param inspectors
     * @return
     */
    public Integer[] needInspectorIds(String[] inspectors){
        Integer[] inspectorIds = new Integer[inspectors.length];
        if(inspectors != null && inspectors.length != 0){
            for(int i = 0; i < inspectors.length;i++){
                inspectorIds[i] = Integer.parseInt(inspectors[i]);
            }
        }
        return inspectorIds;
    }


    @RequestMapping("/add")
    @ResponseBody
    public Map<String,Object> add(PsInspectiontask_main psInspectiontask_main,@RequestParam("inspectorStr") String inspectorStr, HttpSession session,String datetime) throws Exception{
        Map<String,Object> map = new HashMap<>();
        PsInspectiontaskDetails psInspectiontaskDetails = new PsInspectiontaskDetails();//详细任务对象
        //巡检员编号
        String[] inspectors = inspectorStr.split(",");
        Integer[] inspectorIds = new Integer[]{};
        if(!inspectorStr.equals("") && inspectorStr != null){
            inspectorIds = needInspectorIds(inspectors);
        }

        PsUser psUser = (PsUser)session.getAttribute(Constants.LOGIN_USER);

        psInspectiontask_main.setCreatedBy(psUser.getUsername());
        psInspectiontask_main.setIssuedByCode(psUser.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        psInspectiontask_main.setIssuedTime(format.parse(datetime));
        //任务状态
        if(!inspectorStr.equals("") && inspectorStr != null){
            psInspectiontask_main.setTaskStateId(2);
            psInspectiontask_main.setTaskStateName("已分配");
            psInspectiontaskDetails.setTaskStateId(2);
        }else{
            psInspectiontask_main.setTaskStateId(1);
            psInspectiontask_main.setTaskStateName("待分配");
            psInspectiontaskDetails.setTaskStateId(1);
        }
        psInspectiontask_main.setIsCancel(0);

        //添加巡检任务
        inspectiontask_mainDao.add(psInspectiontask_main);
        if(!inspectorStr.equals("")){
            //添加巡检员任务
            inspectorDetailsDao.updateInspectorTask(inspectorIds,psInspectiontask_main.getId());
            //循环添加巡检任务的详细杆塔信息
            psInspectiontaskDetails.setTaskId(psInspectiontask_main.getId());
            psInspectiontaskDetails.setLineCode(psInspectiontask_main.getLineCode());
            psInspectiontaskDetails.setLineName(psInspectiontask_main.getLineName());
            psInspectiontaskDetails.setCreatedBy(psUser.getUsername());
            //查询该线路所有杆塔
            List<PsPoleInfo> psPoleInfoList = poleDao.getLinePole(psInspectiontask_main.getLineId());
            for (PsPoleInfo pole:psPoleInfoList) {
                psInspectiontaskDetails.setPoleId(pole.getId());
                psInspectiontaskDetails.setPoleCode(pole.getPoleCode());
                System.out.println(pole.getPoleCode());
                inspectiontaskDetailsDao.add(psInspectiontaskDetails);
            }
        }

        //修改线路状态
        lineDao.updateLineState(psInspectiontask_main.getLineId());

        map.put("result",true);
        return map;
    }

    @RequestMapping("/InspectorDetialIndex")
    public String InspectorDetialIndex(HttpSession session,String taskId) throws Exception{
        session.setAttribute("taskId",taskId);
        return "system/inspectiontask_main/selectTask";
    }

    @RequestMapping("/get")
    @ResponseBody
    public PsInspectiontask_main get(String taskId) throws Exception{
        return inspectiontask_mainDao.get(Integer.parseInt(taskId));
    }

    @RequestMapping("/getPole")
    @ResponseBody
    public PsInspectiontaskDetails getPole(Integer poleId) throws Exception{
        return inspectiontaskDetailsDao.getPole(poleId);
    }

    @RequestMapping("/getTaskId")
    @ResponseBody
    public PsInspectiontask_main getTaskId(Integer taskId) throws Exception{
        return inspectiontask_mainDao.getTaskId(taskId);
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String,Object> update(PsInspectiontask_main psInspectiontask_main,@RequestParam("inspectorStr") String inspectorStr,String datetime,HttpSession session) throws Exception{
        Map<String,Object> map = new HashMap<>();
        PsInspectiontaskDetails psInspectiontaskDetails = new PsInspectiontaskDetails();//详细任务对象
        ///巡检员编号
        String[] inspectors = inspectorStr.split(",");
        System.out.println(inspectorStr);
        //获取巡检员编号
        Integer[] inspectorIds = new Integer[]{};
        if(!inspectorStr.equals("") && inspectorStr != null){
            inspectorIds = needInspectorIds(inspectors);
        }

        PsUser psUser = (PsUser)session.getAttribute(Constants.LOGIN_USER);

        //任务状态
        if(!inspectorStr.equals("") && inspectorStr != null){
            psInspectiontask_main.setTaskStateId(2);
            psInspectiontask_main.setTaskStateName("已分配");
            psInspectiontaskDetails.setTaskStateId(2);
        }else{
            psInspectiontask_main.setTaskStateId(1);
            psInspectiontask_main.setTaskStateName("待分配");
            psInspectiontaskDetails.setTaskStateId(1);
        }
        psInspectiontask_main.setIsCancel(0);

        //获取修改前任务的线路编号
        PsInspectiontask_main psInspectiontask_main1 = inspectiontask_mainDao.get(psInspectiontask_main.getId());
        //判断是否需要修改线路
        if(psInspectiontask_main1.getLineId() != psInspectiontask_main.getLineId()){
            //根据任务编号删除所有杆塔缺陷信息表
            inspectiontaskDetailsDao.deleteforTaskId(psInspectiontask_main.getId());
            //修改之前任务线路状态
            lineDao.lineState(psInspectiontask_main1.getLineId());
            //修改当前线路状态为检修中
            lineDao.updateLineState(psInspectiontask_main.getLineId());
            //添加杆塔缺陷信息
            //循环添加巡检任务的详细杆塔信息
            psInspectiontaskDetails.setTaskId(psInspectiontask_main.getId());
            psInspectiontaskDetails.setLineCode(psInspectiontask_main.getLineCode());
            psInspectiontaskDetails.setLineName(psInspectiontask_main.getLineName());
            psInspectiontaskDetails.setCreatedBy(psUser.getUsername());
            //查询该线路所有杆塔
            List<PsPoleInfo> psPoleInfoList = poleDao.getLinePole(psInspectiontask_main.getLineId());
            for (PsPoleInfo pole:psPoleInfoList) {
                psInspectiontaskDetails.setPoleId(pole.getId());
                psInspectiontaskDetails.setPoleCode(pole.getPoleCode());
                System.out.println(pole.getPoleCode());
                inspectiontaskDetailsDao.add(psInspectiontaskDetails);
            }
        }

        //修改巡检任务
        psInspectiontask_main.setLastUpdateTime(new Date());
        inspectiontask_mainDao.update(psInspectiontask_main);

        //修改巡检员任务
        if(!inspectorStr.equals("")){
            //添加巡检员任务
            inspectorDetailsDao.updateInspectorTask(inspectorIds,psInspectiontask_main.getId());
        }



        map.put("result",true);
        return map;
    }

    @RequestMapping("/updateInspector")
    @ResponseBody
    public Map<String,Object> updateInspector(PsInspectiontask_main psInspectiontask_main,@RequestParam("inspectorStr") String inspectorStr) throws Exception{
        Map<String,Object> map = new HashMap<>();
        PsInspectiontaskDetails psInspectiontaskDetails = new PsInspectiontaskDetails();//详细任务对象
        System.out.println(psInspectiontask_main.getInspectors());
        ///巡检员编号
        String[] inspectors = inspectorStr.split(",");
        //获取巡检员编号
        Integer[] inspectorIds = new Integer[]{};
        if(!inspectorStr.equals("") && inspectorStr != null){
            inspectorIds = needInspectorIds(inspectors);
        }

        //修改巡检员任务
        if(!inspectorStr.equals("")){
            //添加巡检员任务
            inspectorDetailsDao.updateInspectorTask(inspectorIds,psInspectiontask_main.getId());
        }
        //修改任务状态
        inspectiontask_mainDao.updateTaskStateAll(psInspectiontask_main.getId(),2,"已分配");
        //修改任务巡检员列
        inspectiontask_mainDao.updateInspectors(psInspectiontask_main.getId(),psInspectiontask_main.getInspectors());
        map.put("result",true);
        return map;
    }

    @RequestMapping("/cancelTask")
    @ResponseBody
    public Map<String,Object> cancelTask(Integer taskId,Integer lineId) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //修改任务状态
        inspectiontask_mainDao.updateTaskState(taskId);
        //修改巡检员状态
        inspectorDetailsDao.updateInspectorTaskId(taskId);
        //修改线路状态
        lineDao.lineState(lineId);
        //删除线路任务详细信息
        inspectiontaskDetailsDao.deleteforTaskId(taskId);
        map.put("result",true);
        return map;
    }

    @RequestMapping("/open")
    @ResponseBody
    public Map<String,Object> open(Integer taskId) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //修改巡检任务状态
        inspectiontask_mainDao.updateTaskStateAll(taskId,3,"执行中");
        map.put("result",true);
        return map;
    }
}
